// pages/main-safety/safety.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    submiting:false,
    uploadflag:false,
    currentDriver:{},
    currentCar:{},
    checkImages: [],
    checktype: ['*车前牌照和安全员合照', '*安全锤和三角牌', '*灭火器有效期', '*车辆内饰', '*应急出口标志', '*轮胎照片','*雨刮器'],
    checktype1: ['*车前牌照和安全员合照', '*灭火器和三角牌', '*导除静电装置', '*轮胎', '*安全检查','*安全检查'],
    userInfo: {},
    bususer: {},
    checkForm:{
      checkTime:"",
      checkUserName:"",
      checkUserId:"",
      tailCarId:"",
      rectItem:"",
      rectTotal:"",
      isRect:"",
      isLight:"0",
      isTurnto:"0",
      isRun:"0",
      isTyre:"0",
      isSafeDoor:"0",
      isSwitch:"0",
      isExit:"0",
      isFire:"0",
      isSafeHammer:"0",
      isSafeBelt:"0",
      isWarnTriangle:"0",
      isGPS:"0",
      isDriveSus:"0",
      isTanksTires:"0",
      isFireEqu:"0",
      isDangerMark:"0",
      isElectDevice:"0",
      isSparkDevice:"0",
      isFlameArres:"0",
      isValve:"0",
      isTankInte:"0",
      isFastenParts:"0",
      isProtectArti:"0",
      onePicUrlId:"",
      twoPicUrlId:"",
      threePicUrlId:"",
      fourPicUrlId:"",
      fivePicUrlId:"",
      sixPicUrlId:"",
      sevenPicUrlId:"",
      eightPicUrlId:"",
      ninePicUrlId:"",
      driverUser:{
        id:""
      },
      car:{
        id:""
      }

    },
    zhenggaiImages:[],
    tailCar:{},
    rectItem:"",
    rectTotal:0,
    radioItem:{
      isLight: "0",
      isTurnto: "0",
      isRun: "0",
      isTyre: "0",
      isSafeDoor: "0",
      isSwitch: "0",
      isExit: "0",
      isFire: "0",
      isSafeHammer: "0",
      isSafeBelt: "0",
      isWarnTriangle: "0",
      isGPS: "0",
      isDriveSus: "0",
      isTanksTires: "0",
      isFireEqu: "0",
      isDangerMark: "0",
      isElectDevice: "0",
      isSparkDevice: "0",
      isFlameArres: "0",
      isValve: "0",
      isTankInte: "0",
      isFastenParts: "0",
      isProtectArti: "0"
    }
  },
  initImages: function (num) {
    var result = [];
    for (var i = 0; i < num; i++) {
      var img = {
        filePath: "",
        hasImage: false,
        index: i,
        imageUrl:""
      }
      result.push(img);
    }
    this.setData({ checkImages: result });
  },
  chooseImageUi: function (event) {
    var that = this;
    var num = event.currentTarget.dataset.index;
    var currentImage = this.data.checkImages[num];
    wx.chooseImage({
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        
        that.uploadImage(res.tempFilePaths[0],function(data){ 
          currentImage.hasImage = true;
          currentImage.imageUrl = data.url;
          currentImage.filePath = data.url;
          that.data.checkImages[num] = currentImage;
          that.setData({ checkImages: that.data.checkImages });
        })
        
      }
    })
  },
  removeimage: function (event) {
    var num = event.currentTarget.dataset.index;
    var currentImage = this.data.checkImages[num];
    currentImage.hasImage = false;
    currentImage.filePath = "";
    currentImage.imageUrl="";
    this.data.checkImages[num] = currentImage;
    this.setData({ checkImages: this.data.checkImages });
  },

  uploadImage:function(filePath,callback){
    var that=this;
    wx.showLoading({
      title: '上传图片中'
    });
    this.setData({uploadflag:true});
    wx.uploadFile({
      url: app.globalData.serverPath + 'api/upload-pic-two',
      filePath: filePath,
      name: 'myfile',
      formData: {
        'lat': app.globalData.latitude,
        'lng': app.globalData.longitude
      },
      success:function(res){
        var data = res.data
        var urldata = JSON.parse(res.data);
        if(urldata&&urldata.url!="null"){
          if (callback) {
            callback(urldata);
          }
        }else{
          wx.showModal({
            title: '错误提示',
            content: '照片上传失败，请重试',
            showCancel:false
          })
        }
        
      },
      complete:function(){
        wx.hideLoading();
        that.setData({ uploadflag: false });
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that=this;
    this.initImages(9);
    console.log(app.globalData.userInfo)
    if (app.globalData.userInfo && app.globalData.bususer) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true,
        bususer: app.globalData.bususer
      })
    } else {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: app.globalData.userInfo,
          hasUserInfo: true,
          bususer: app.globalData.bususer
        })
      }
    }
    if(app.globalData.checkCar){
      this.setData({ currentCar: app.globalData.checkCar});
    }
    if (app.globalData.checkDriver) {
      this.setData({ currentDriver: app.globalData.checkDriver });
    }

    //如果是指定id的修改
    if(options.checkid){
      wx.showLoading({
        title: '加载检查数据'
      })
      wx.request({
        method: "POST",
        url: app.globalData.serverPath + 'api/bs-car-safe-checks-create?check_id=' + options.checkid,
        header: {
          'Authorization': app.globalData.token
        },
        success:function(res){
          wx.hideLoading();
          console.log("onload checkid",res);
          if(res.statusCode!=200){
            wx.showModal({
              title: '错误提示',
              content: '加载检查数据出错',
              showCancel: false
            })
          }else{
            
          }
        }
      })
    }


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
      if(app.globalData.latitude==null || app.globalData.longitude==null){
          wx.getLocation({
              type: 'wgs84',
              success: function (res) {
                  var latitude = res.latitude
                  var longitude = res.longitude
                  console.log("getlocation>>>",res);
                  app.globalData.latitude = latitude;
                  app.globalData.longitude = longitude;
              },
              fail:function(error){

              }
          })
      }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var date=new Date();
    this.setData({checkMonth:date.getFullYear()+""+(date.getMonth()+1)});
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },

  gotozhenggai:function(){
    if(!this.data.currentCar){
      wx.showModal({
        title: '错误提示',
        content: '请先选择检查车辆',
        showCancel:false
      })
      return;
    }
    wx.navigateTo({
      url: '../zhenggai/zhenggai?carid=' + this.data.currentCar.id + "&month=" + this.data.checkMonth
    })
  },

  radioChange:function(e){
    var attr = e.currentTarget.dataset.attr;
    this.data.radioItem[attr + ""] = e.detail.value
  },

//验证图片选择
  validatePic:function(formdata){
    if (this.data.currentCar.carClass==1){//货车
      if (!formdata.onePicUrlId||formdata.onePicUrlId==""){
        wx.showModal({
          title: '错误提示',
          content: '请上传[车前牌照和安全员合照]照片',
          showCancel: false
        })
        return false;
      }
      if (!formdata.twoPicUrlId || formdata.twoPicUrlId == "") {
        wx.showModal({
          title: '错误提示',
          content: '请上传[灭火器和三角牌]照片',
          showCancel: false
        })
        return false;
      }
      if (!formdata.threePicUrlId || formdata.threePicUrlId == "") {
        wx.showModal({
          title: '错误提示',
          content: '请上传[导除静电装置]照片',
          showCancel: false
        })
        return false;
      }
      if (!formdata.fourPicUrlId || formdata.fourPicUrlId == "") {
        wx.showModal({
          title: '错误提示',
          content: '请上传[轮胎]照片',
          showCancel: false
        })
        return false;
      }
      if (!formdata.fivePicUrlId || formdata.fivePicUrlId == "") {
        wx.showModal({
          title: '错误提示',
          content: '请上传[安全检查]照片',
          showCancel: false
        })
        return false;
      }
    } else if (this.data.currentCar.carClass == 0){
      if (!formdata.onePicUrlId || formdata.onePicUrlId == "") {
        wx.showModal({
          title: '错误提示',
          content: '请上传[车前牌照和安全员合照]照片',
          showCancel: false
        })
        return false;
      }
      if (!formdata.twoPicUrlId || formdata.twoPicUrlId == "") {
        wx.showModal({
          title: '错误提示',
          content: '请上传[安全锤和三角牌]照片',
          showCancel: false
        })
        return false;
      }
      if (!formdata.threePicUrlId || formdata.threePicUrlId == "") {
        wx.showModal({
          title: '错误提示',
          content: '请上传[灭火器有效期]照片',
          showCancel: false
        })
        return false;
      }
      if (!formdata.fourPicUrlId || formdata.fourPicUrlId == "") {
        wx.showModal({
          title: '错误提示',
          content: '请上传[车辆内饰]照片',
          showCancel: false
        })
        return false;
      }
      if (!formdata.fivePicUrlId || formdata.fivePicUrlId == "") {
        wx.showModal({
          title: '错误提示',
          content: '请上传[应急出口标志]照片',
          showCancel: false
        })
        return false;
      }
      if (!formdata.sixPicUrlId || formdata.sixPicUrlId == "") {
        wx.showModal({
          title: '错误提示',
          content: '请上传[轮胎]照片',
          showCancel:false
        })
        return false;
      }
      if (!formdata.sevenPicUrlId || formdata.sevenPicUrlId == "") {
        wx.showModal({
          title: '错误提示',
          content: '请上传[雨刮器]照片',
          showCancel: false
        })
        return false;
      }
    }
    return true;
  },

  getformdata:function(){
    var checktime=new Date();
    var formdata = {
      checkTime: "",
      checkUserName: app.globalData.bususer.trueName,
      checkUserId: app.globalData.bususer.id,
      tailCarId: this.data.tailCar.id ? this.data.tailCar.id:"",
      rectItem: this.data.rectItem,
      rectTotal:this.data.rectTotal,
      isRect: (this.data.rectTotal>0)?1:0,
      isLight: this.data.radioItem.isLight,
      isTurnto: this.data.radioItem.isTurnto,
      isRun: this.data.radioItem.isRun,
      isTyre: this.data.radioItem.isTyre,
      isSafeDoor: this.data.radioItem.isSafeDoor,
      isSwitch: this.data.radioItem.isSwitch,
      isExit: this.data.radioItem.isExit,
      isFire: this.data.radioItem.isFire,
      isSafeHammer: this.data.radioItem.isSafeHammer,
      isSafeBelt: this.data.radioItem.isSafeBelt,
      isWarnTriangle: this.data.radioItem.isWarnTriangle,
      isGPS: this.data.radioItem.isGPS,
      isDriveSus: this.data.radioItem.isDriveSus,
      isTanksTires: this.data.radioItem.isTanksTires,
      isFireEqu: this.data.radioItem.isFireEqu,
      isDangerMark: this.data.radioItem.isDangerMark,
      isElectDevice: this.data.radioItem.isElectDevice,
      isSparkDevice: this.data.radioItem.isSparkDevice,
      isFlameArres: this.data.radioItem.isFlameArres,
      isValve: this.data.radioItem.isValve,
      isTankInte: this.data.radioItem.isTankInte,
      isFastenParts: this.data.radioItem.isFastenParts,
      isProtectArti: this.data.radioItem.isProtectArti,
      onePicUrlId: this.data.checkImages[0].imageUrl,
      twoPicUrlId: this.data.checkImages[1].imageUrl,
      threePicUrlId: this.data.checkImages[2].imageUrl,
      fourPicUrlId: this.data.checkImages[3].imageUrl,
      fivePicUrlId: this.data.checkImages[4].imageUrl,
      sixPicUrlId: this.data.checkImages[5].imageUrl,
      sevenPicUrlId: this.data.checkImages[6].imageUrl,
      eightPicUrlId: this.data.checkImages[7].imageUrl,
      ninePicUrlId: this.data.checkImages[8].imageUrl,
      driverUser: {
        id:this.data.currentDriver.id
      },
      car: {
        id:this.data.currentCar.id,
        carClass: this.data.currentCar.carClass
      }

    };

    console.log("formdata",formdata);
    return formdata;
  },

  initformdata:function(formdata){

  },

  submit:function(){
    var that=this;
    //如果正在上传图片，不提交
    if (this.data.uploadflag){
      return;
    }
    //如果正在提交中，不重复提交
    if (this.data.submiting){
      return;
    }
    var formdata=this.getformdata();
    if (!formdata.car.id || formdata.car.id == "") {
      wx.showModal({
        title: '错误提示',
        content: '请选择检查车辆',
        showCancel: false
      })
      return;
    }
    if (!formdata.driverUser.id || formdata.driverUser.id==""){
      wx.showModal({
        title: '错误提示',
        content: '请选择驾驶员',
        showCancel: false
      })
      return;
    }
    // if (formdata.car.carClass == 1 || formdata.car.carClass == "1" ) {
    //   if (!formdata.tailCarId || formdata.tailCarId==""){
    //     wx.showModal({
    //       title: '错误提示',
    //       content: '请选择挂车车牌',
    //       showCancel: false
    //     })
    //     return;
    //   }
      
    // }

    if (!this.validatePic(formdata)){
      return;
    }
    wx.showLoading({
      title: '正在提交数据'
    })
    this.setData({submiting:true});
    wx.request({
      method:"POST",
      url: app.globalData.serverPath + 'api/bs-car-safe-checks-create?checkItemImgUrls=' + this.data.zhenggaiImages,
      header: {
        'Authorization': app.globalData.token
      },
      data:formdata,
      success:function(res){
        console.log("submit check",res);
        wx.hideLoading();
        if(res.statusCode!=200){
          wx.showModal({
            title: '错误提示',
            content: "数据保存出错",
            showCancel:false
          });
        }else{
          if(res.data.stat>0){
            wx.showToast({
              title: '数据保存成功',
              success: function () {
                wx.navigateBack();
              }
            });
          }else{
            wx.showModal({
              title: '错误提示',
              content: res.data.message,
              showCancel: false
            });
          }
         
        }
      },
      fail:function(error){
        wx.showModal({
          title: '错误提示',
          content: "数据保存出错",
          showCancel: false
        });
      },
      complete:function(){
        that.setData({submiting: false });
      }
    })

  }


})